package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.advice.OneAnnotation;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.OneException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private EmpLogService empLogService;

    @Autowired
    private DeptService deptService;

    @Override
    public PageResult page(EmpQueryParam empQueryParam) {
        IPage<Emp> page = new Page<>(empQueryParam.getPage(), empQueryParam.getPageSize());

        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(empQueryParam.getName() != null, Emp::getName, empQueryParam.getName());
        queryWrapper.eq(empQueryParam.getGender() != null, Emp::getGender, empQueryParam.getGender());
        queryWrapper.between(empQueryParam.getBegin() != null && empQueryParam.getEnd() != null, Emp::getEntryDate, empQueryParam.getBegin(), empQueryParam.getEnd());

        page = page(page, queryWrapper);

        List<Emp> empList = page.getRecords();
        empList.forEach(emp -> {
            if (emp.getDeptId() != null) {
            Dept dept = deptService.getById(emp.getDeptId());
            if (dept != null) {
                emp.setDeptName(dept.getName());
            }
        }});
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(LocalDateTime.now());
        this.save(emp);

        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && exprList.size() > 0) {
            exprList.forEach(empExpr -> {
                empExpr.setEmpId(emp.getId());
            });
            empExprMapper.insert(exprList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteEmp(List<Integer> ids) {
        this.removeByIds(ids);
        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EmpExpr::getEmpId, ids);
        empExprMapper.delete(queryWrapper);
    }

    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = this.getById(id);

        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmpExpr::getEmpId, id);
        List<EmpExpr> exprList = empExprMapper.selectList(queryWrapper);
        emp.setExprList(exprList);

        return emp;
    }

    @Override
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);

        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(EmpExpr::getEmpId, emp.getId());
        empExprMapper.delete(queryWrapper);

        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(empExpr -> {
            empExpr.setEmpId(emp.getId());
        });
        empExprMapper.insert(exprList);

    }

    @Override
    public LoginInfo login(EmpDto empDto) {
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Emp::getUsername, empDto.getUsername());
        queryWrapper.eq(Emp::getPassword, empDto.getPassword());
        Emp emp = empMapper.selectOne(queryWrapper);
        if (emp != null) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("id", emp.getId());
            dataMap.put("username", emp.getUsername());

            String jwt = JwtUtils.generateJwt(dataMap);
            return new LoginInfo(emp.getId(), emp.getUsername(), emp.getName(), jwt);
        }
        return null;

    }

    //    @Override
//    public PageResult page(EmpQueryParam empQueryParam) {
//        //设置分页参数
//        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
//        // 执行查询
////        Long total = empMapper.findCount();
//        Page<Emp> empPage = (Page<Emp>) empMapper.getList(empQueryParam);
////        Integer skip = (page - 1) * pageSize;
//        long total = empPage.getTotal();
//        List<Emp> rows = empPage.getResult();
//
//        return new PageResult<>(total, rows);
//    }
//
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public void save(Emp emp) throws Exception {
//        // 1. 保存员工基本信息
//        emp.setCreateTime(LocalDateTime.now());
//        emp.setUpdateTime(LocalDateTime.now());
//
//        empMapper.insert(emp);
//
//        EmpLog empLog = new EmpLog(null, LocalDateTime.now(), emp.toString());
//        empLogService.insertLog(empLog);
//
////        if (true) {
////            throw new Exception("出现了异常");
////        }
//        // 2. 保存员工工作经历  -- 批量
//        List<EmpExpr> exprList = emp.getExprList();
//        if (exprList != null && exprList.size() > 0) {
//            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
//            empExprMapper.insertBatch(exprList);
//        }
//    }
//
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public void delete(List<Integer> ids) {
//        empMapper.deleteByIds(ids);
//
//        empExprMapper.delete(ids);
//    }
//
//
//    @Override
//    public Emp getById(Integer id) {
//        Emp emp = empMapper.selectById(id);
//
//        List<EmpExpr> exprList = empExprMapper.getById(id);
//        emp.setExprList(exprList);
//        return emp;
//    }
//
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public void update(Emp emp) {
//        emp.setUpdateTime(LocalDateTime.now());
//        empMapper.updateById(emp);
//
//        empExprMapper.delete(Arrays.asList(emp.getId()));
//
//        List<EmpExpr> exprList = emp.getExprList();
//        if (exprList != null && exprList.size() > 0) {
//            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
//            empExprMapper.insertBatch(exprList);
//        }
//    }
//
    @Override
    public JobOption getEmpJobData() {
        List<Map<String, Integer>> list = empMapper.getEmpJobData();
        List jobList = new ArrayList<>();
        List dataList = new ArrayList<>();

        for (Map<String, Integer> map : list) {
            jobList.add(map.get("jobName"));
            dataList.add(map.get("total"));
        }
        JobOption jobOption = new JobOption(jobList, dataList);
        return jobOption;
    }

    @Override
    public List<Map> getEmpGender() {
        List<Map> list = empMapper.getEmpGender();
        return list;
    }

    @Override
    public List getDegree() {
        return empMapper.getDegree();
    }

    @Override
    public ClazzOption getCount() {
        List<Map<String, Integer>> mapList = empMapper.getCount();
        List clazzList = new ArrayList<>();
        List dataList = new ArrayList<>();

        for (Map map : mapList) {
            clazzList.add(map.get("name"));
            dataList.add(map.get("date"));
        }
        ClazzOption clazzOption = new ClazzOption(clazzList, dataList);
        return clazzOption;
    }
//
//    @Override
//    public List<Emp> getEmp() {
//        return empMapper.getEmp();
//    }
//
////    @Override
////    public LoginInfo login(EmpDto empDto) {
////        Emp empLogin = empMapper.getUsernameAndPassword(empDto.getUsername(),empDto.getPassword());
////        if (empLogin !=null) {
////            Map<String, Object> dataMap = new HashMap<>();
////            dataMap.put("id",empLogin.getId());
////            dataMap.put("username",empLogin.getUsername());
////
////            String jwt = JwtUtils.generateJwt(dataMap);
////            return new LoginInfo(empLogin.getId(),empLogin.getUsername(),empLogin.getName(),jwt);
////        }
////        return null;
////    }
//
//    @Override
//    public LoginInfo login(EmpDto empDto) {
//        Emp emp = empMapper.getUsernameAndPassword(empDto.getUsername(), empDto.getPassword());
//        if (emp == null) {
//            throw new OneException("用户名或密码错误");
//        }
//        Map<String, Object> dataMap = new HashMap<>();
//        dataMap.put("id", emp.getId());
//        dataMap.put("username", emp.getUsername());
//
//        String token = JwtUtils.generateJwt(dataMap);
//        return new LoginInfo(emp.getId(), emp.getUsername(), emp.getName(), token);
//    }


}
